package com.wxj.book.cms.controller;

import com.github.pagehelper.PageInfo;
import com.wxj.book.cms.common.ServerResponse;
import com.wxj.book.cms.pojo.User;
import com.wxj.book.cms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 带有分页获取所有的用户
     */
    @RequestMapping("user/getAll")
    public String getAll(@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                         @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                         ModelMap modelMap) {
        PageInfo<User> pageInfo = userService.getAll(pageNum, pageSize);
        modelMap.addAttribute("pageInfo", pageInfo);
        return "user";

    }

    /**
     * 删除用户
     */
    @RequestMapping("user/deleteById")
    @ResponseBody
    public ServerResponse deleteById(@RequestParam("userId") Integer userId) {
        if (userId == null) {
            return ServerResponse.createByErrorMessage("删除失败！");
        }
        int result = userService.deleteById(userId);
        if (result > 0) {
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }

    /**
     * 更新用户信息
     */
    @PostMapping("user/updateUser")
    @ResponseBody
    public ServerResponse updateUser(User user) {
        if (user == null) {
            return ServerResponse.createByErrorMessage("更新失败");
        }
        int result = userService.updateUser(user);
        if (result > 0) {
            return ServerResponse.createBySuccessMessage("更新成功");
        }
        return ServerResponse.createByErrorMessage("更新失败");
    }
}
